//
//  MovieListViewController.m
//  Kokozu
//
//  Created by Bismarrck on 11-7-12.
//  Copyright 2011年 Tsinghua University. All rights reserved.
//

#import "MovieListViewController.h"
#import "MovieDetailViewController.h"
#import "NYOPMovieListCell.h"
#import "CustomTabBarViewController.h"


@interface MovieListViewController ()

- (void)pushToLocationView;
- (void)reloadTableViewDataSource;
- (void)doneLoadingTableViewData;

@end


@implementation MovieListViewController

@synthesize normalCellNib = normalCellNib_;
@synthesize expandCellNib = expandCellNib_;
@synthesize normalTmpCell = normalTmpCell_;
@synthesize expandTmpCell = expandTmpCell_;
@synthesize selectedIndexPath = selectedIndexPath_;
@synthesize tableFooterCell = tableFooterCell_;
@synthesize rowsCount = rowsCount_;
@synthesize cellIsExpanded;
@synthesize locationCircles;


- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

- (void)dealloc
{
    refreshTableHeaderView_ = nil;
    
    [normalTmpCell_ release];
    [normalCellNib_ release];
    [expandTmpCell_ release];
    [expandCellNib_ release];
    [selectedIndexPath_ release];
    [tableFooterCell_ release];
    
    [super dealloc];
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    // Configure the table view
    self.tableView.autoresizingMask = UIViewAutoresizingNone;    
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.separatorColor = [UIColor clearColor];
    
    // Set the location button on the navigation bar
    [self createBarItemOn:kNavBarItemSideRight frame:kNavBarRigthItemFrameWithPrompt title:@"更改位置" target:self action:@selector(pushToLocationView)];
    
    // Set the refresh table header view
    if (refreshTableHeaderView_ == nil) {
		
		EGORefreshTableHeaderView *view = [[EGORefreshTableHeaderView alloc] initWithFrame:CGRectMake(0.0f, 0.0f - self.tableView.bounds.size.height, self.view.frame.size.width, self.tableView.bounds.size.height)];
		view.delegate = self;
		[self.tableView addSubview:view];
		refreshTableHeaderView_ = view;
		[view release];
		
	}
	// update the last update date
	[refreshTableHeaderView_ refreshLastUpdatedDate];
    
    // Load the cell nib file
    normalCellNib_ = [self normalCellNib];
    expandCellNib_ = [self expandCellNib];
    selectedIndexPath_ = nil;
    
    // Set the default rows count
    rowsCount_ = 7;
    
    // Set the location data
    NSMutableArray *circle_array = [[NSMutableArray alloc] init];
    for (int i = 0; i < 4; i++) {
        CommCircle *aCircle = [[CommCircle alloc] init];
        NSMutableArray *area_array = [[NSMutableArray alloc] init];
        for (int j = 0; j < 8; j++) {
            CommArea *area = [[CommArea alloc] init];
            area.areaName = [NSString stringWithFormat:@"子商圈%d", j];
            [area_array addObject:area];
            [area release];
        }
        aCircle.circleName = [NSString stringWithFormat:@"商圈%d", i];
        aCircle.commAreas = area_array;
        [area_array release];
        
        [circle_array addObject:aCircle];
        [aCircle release];
    }
    
    self.locationCircles = circle_array;
    [circle_array release];
}

- (void)viewDidUnload
{
    refreshTableHeaderView_ = nil;
    
    [super viewDidUnload];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark -
#pragma mark - Table View Data Source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 7;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIdentifier = @"CellIdentifier";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier] autorelease];
    }
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == rowsCount_ - 1) {
        return 60.0f;
    }
    else if (selectedIndexPath_ == indexPath && cellIsExpanded == NO) {
        return [self expandCellHeight];
    }
    else if (selectedIndexPath_ == indexPath && cellIsExpanded == YES) {
        return [self normalCellHeight];
    }
    else {
        return [self normalCellHeight];
    }
}

#pragma mark -
#pragma mark - Table View Delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.selectedIndexPath == indexPath) {
        NSArray *rowsToNormal = [NSArray arrayWithObject:self.selectedIndexPath];
        [self.tableView beginUpdates];
        if (cellIsExpanded == NO) {
            UITableViewRowAnimation normalAniamtion = UITableViewRowAnimationFade;
            [self.tableView reloadRowsAtIndexPaths:rowsToNormal withRowAnimation:normalAniamtion];
            [self.tableView endUpdates];
            cellIsExpanded = YES;
        }
        else {
            UITableViewRowAnimation normalAniamtion = UITableViewRowAnimationFade;
            [self.tableView reloadRowsAtIndexPaths:rowsToNormal withRowAnimation:normalAniamtion];
            [self.tableView endUpdates];
            cellIsExpanded = NO;
        }
    }
    else if (self.selectedIndexPath != indexPath && self.selectedIndexPath != nil) {
        NSArray *rowsToExpand = [NSArray arrayWithObject:indexPath];
        NSArray *rowsToNormal = [NSArray arrayWithObject:self.selectedIndexPath];
        [self.tableView beginUpdates];
        self.selectedIndexPath = indexPath;
        cellIsExpanded = NO;
        UITableViewRowAnimation expandAnimation;
        UITableViewRowAnimation normalAniamtion;
        if (indexPath.row > self.selectedIndexPath.row) {
            expandAnimation = UITableViewRowAnimationFade;
            normalAniamtion = UITableViewRowAnimationFade;
        }
        else {
            expandAnimation = UITableViewRowAnimationFade;
            normalAniamtion = UITableViewRowAnimationFade;
        }
        
        [self.tableView reloadRowsAtIndexPaths:rowsToNormal withRowAnimation:normalAniamtion];
        [self.tableView reloadRowsAtIndexPaths:rowsToExpand withRowAnimation:expandAnimation];
        [self.tableView endUpdates];
        cellIsExpanded = YES;
    }
    else if (self.selectedIndexPath == nil) {
        NSArray *rowsToExpand = [NSArray arrayWithObject:indexPath];
        [self.tableView beginUpdates];
        self.selectedIndexPath = indexPath;
        [self.tableView reloadRowsAtIndexPaths:rowsToExpand withRowAnimation:UITableViewRowAnimationFade];
        [self.tableView endUpdates];
        cellIsExpanded = YES;
    }
    
    [self.tableView deselectRowAtIndexPath:indexPath animated:NO];
}

#pragma mark -
#pragma mark UIScrollViewDelegate Methods

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{	
	
	[refreshTableHeaderView_ egoRefreshScrollViewDidScroll:scrollView];
    
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
	
	[refreshTableHeaderView_ egoRefreshScrollViewDidEndDragging:scrollView];
	
}


#pragma mark -
#pragma mark EGORefreshTableHeaderDelegate Methods

- (void)egoRefreshTableHeaderDidTriggerRefresh:(EGORefreshTableHeaderView*)view{
	
	[self reloadTableViewDataSource];
	
    if (![self egoRefreshTableHeaderDataSourceIsLoading:refreshTableHeaderView_]) {
        [self performSelector:@selector(doneLoadingTableViewData) 
                   withObject:nil 
                   afterDelay:1.0];
    }
	
}

- (BOOL)egoRefreshTableHeaderDataSourceIsLoading:(EGORefreshTableHeaderView*)view{
	
	return isReloading_; // should return if data source model is reloading
	
}

- (NSDate*)egoRefreshTableHeaderDataSourceLastUpdated:(EGORefreshTableHeaderView*)view{
	
	return [NSDate date]; // should return date data source was last changed
	
}

#pragma mark -
#pragma makr - Private methods

- (void)pushToLocationView
{
    NSMutableArray *circle_array = [[NSMutableArray alloc] init];
    for (int i = 0; i < 4; i++) {
        NSMutableArray *array = [[NSMutableArray alloc] init];
        for (int j = 0; j < 5; j++) {
            CommArea *area = [[CommArea alloc] init];
            area.areaName = [NSString stringWithFormat:@"子商圈%d%d",i,j];
            [array addObject:area];
            [area release];
        }
        CommCircle *aCircle = [[CommCircle alloc] init];
        aCircle.commAreas = array;
        aCircle.circleName = [NSString stringWithFormat:@"商圈%d", i];
        [circle_array addObject:aCircle];
        [aCircle release];
    }
    
    CustomTabBarViewController *sharedController = [CustomTabBarViewController sharedTabBarController];
    [sharedController.tabBar setHidden:YES];
    LocationViewController *locationViewController = [[LocationViewController alloc] initWithStyle:UITableViewStylePlain delegate:nil commCirles:circle_array];
    UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:locationViewController];
    locationViewController.view.frame = CGRectMake(0, 0, 320, 480);
    [sharedController.view bringSubviewToFront:navigationController.view];
    [self presentModalViewController:navigationController animated:YES];
    [locationViewController release];
}

- (void)reloadTableViewDataSource
{
    isReloading_ = YES;
    
    // call the data model to reload data
    
    isReloading_ = NO;
}

- (void)doneLoadingTableViewData
{
    // Reload the table view or table view sections
    [self.tableView reloadData];
    
    // Set the header view state
    [refreshTableHeaderView_ egoRefreshScrollViewDataSourceDidFinishedLoading:self.tableView];
}

- (MovieDetailViewController *)nextViewControllerForIndexPath:(NSIndexPath *)indexPath
{
    return nil;
}

- (void)accessoryButtonTapped:(id)sender
{
    UIButton *button = (UIButton *)sender;
    [self.navigationController pushViewController:[self nextViewControllerForIndexPath:[NSIndexPath indexPathForRow:button.tag inSection:0]] animated:YES];
}

- (UINib *)normalCellNib
{
    return nil;
}

- (UINib *)expandCellNib
{
    return nil;
}

- (CGFloat)normalCellHeight
{
    return 0;
}

- (CGFloat)expandCellHeight
{
    return 0;
}

- (void)configureCell:(KKZBaseCell *)cell atIndexPath:(NSIndexPath *)indexPath options:(CellState)state
{
    
}

#pragma mark -
#pragma mark - Table Footer View Delegate

- (void)updatingWillStart
{
    [self performSelector:@selector(updatingDidFinish) withObject:nil afterDelay:4.0];
}

- (void)updatingDidFinish
{
    [tableFooterCell_ refreshDidFinished];
}

@end
